package com.ruoyi.web.controller.wechat;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wechat.domain.MsgTemplate;
import com.ruoyi.wechat.domain.TemplateMsgBatchForm;
import com.ruoyi.wechat.service.MsgTemplateService;
import com.ruoyi.wechat.service.TemplateMsgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;


/**
 * 消息模板
 *
 * @author netstat -ano | findstr 8000
 * @date 2021-11-09
 */
@Slf4j
@RestController
@RequestMapping("/manage/msgTemplate")
@Api(tags = {"消息模板-管理后台", "模板消息的模板"})
public class MsgTemplateManageController {
    @Resource
    private MsgTemplateService msgTemplateService;
    @Resource
    private TemplateMsgService templateMsgService;
    @Autowired
    private WxMpService wxMpService;

    /**
     * 列表
     */
    @PreAuthorize("@ss.hasPermi('wx:msgTemplate:list')")
    @GetMapping("/list")
    @ApiOperation(value = "列表")
    public AjaxResult list(Page page, MsgTemplate msgTemplate) {
        QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<MsgTemplate>()
                .eq(StringUtils.hasText(msgTemplate.getAppid()), "appid", msgTemplate.getAppid())
                .like(StringUtils.hasText(msgTemplate.getTitle()), "title", msgTemplate.getTitle());
        Page page1 = msgTemplateService.page(page, queryWrapper);
        return AjaxResult.success(page1);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "详情-通过ID")
    public AjaxResult info(@PathVariable("id") Long id) {
        MsgTemplate msgTemplate = msgTemplateService.getById(id);

        return AjaxResult.success("msgTemplate", msgTemplate);
    }

    /**
     * 信息
     */
    @GetMapping("/getByName")
    @ApiOperation(value = "详情-通过名称")
    public AjaxResult getByName(String name) {
        MsgTemplate msgTemplate = msgTemplateService.selectByName(name);

        return AjaxResult.success("msgTemplate", msgTemplate);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation(value = "保存")
    public AjaxResult save(@RequestBody MsgTemplate msgTemplate) {
        msgTemplateService.save(msgTemplate);

        return AjaxResult.success();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public AjaxResult update(@RequestBody MsgTemplate msgTemplate) {
        msgTemplateService.updateById(msgTemplate);

        return AjaxResult.success();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    public AjaxResult delete(@RequestBody String[] ids) {
        msgTemplateService.removeByIds(Arrays.asList(ids));
        return AjaxResult.success();
    }

    /**
     * 同步公众号模板
     */
    @PostMapping("/syncWxTemplate/{appid}")
    @ApiOperation(value = "同步公众号模板")
    public AjaxResult syncWxTemplate(@PathVariable String appid) {
        this.wxMpService.switchoverTo(appid);
        try {
            msgTemplateService.syncWxTemplate(appid);
        } catch (WxErrorException e) {
            log.info("同步公众号模板异常：{}", e);
        }
        return AjaxResult.success();
    }

    /**
     * 批量向用户发送模板消息
     * 通过用户筛选条件（一般使用标签筛选），将消息发送给数据库中所有符合筛选条件的用户
     */
    @PostMapping("/sendMsgBatch")
    @ApiOperation(value = "批量向用户发送模板消息", notes = "将消息发送给数据库中所有符合筛选条件的用户")
    public AjaxResult sendMsgBatch(String appid, @RequestBody TemplateMsgBatchForm form) {
        this.wxMpService.switchoverTo(appid);
        templateMsgService.sendMsgBatch(form, appid);
        return AjaxResult.success();
    }


}
